mod config;
mod ftp;
mod auth;
mod database;
mod filesystem;
mod utils;
mod services;

use anyhow::Result;
use clap::Parser;
use tracing::{info, error};
use tracing_subscriber;

use config::ServerConfig;
use ftp::server::FtpServer;

#[derive(Parser)]
#[command(name = "ftp-server")]
#[command(about = "A high-performance FTP server with encryption plugin support")]
struct Args {
    /// Configuration file path
    #[arg(short, long, default_value = "config/server.toml")]
    config: String,
    
    /// Enable debug logging
    #[arg(short, long)]
    debug: bool,
}

#[tokio::main]
async fn main() -> Result<()> {
    let args = Args::parse();
    
    // 初始化日志
    init_logging(args.debug)?;
    
    info!("Starting FTP Server...");
    
    // 加载配置
    let config = ServerConfig::load(&args.config)?;
    info!("Configuration loaded from: {}", args.config);
    
    // 初始化数据库
    let db = database::Database::new(&config.database.path).await?;
    db.run_migrations().await?;
    info!("Database initialized");
    
    // 创建FTP服务器
    let server = FtpServer::new(config, db).await?;
    
    // 启动服务器
    if let Err(e) = server.start().await {
        error!("Server error: {}", e);
        return Err(e);
    }
    
    Ok(())
}

fn init_logging(debug: bool) -> Result<()> {
    let level = if debug { "debug" } else { "info" };
    
    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::new(level))
        .with_target(false)
        .with_thread_ids(true)
        .with_thread_names(true)
        .init();
    
    Ok(())
}
